package com.fvision.camera.view.fragment;//v4注释整个类

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.fvision.camera.R;
import com.fvision.camera.bean.FileBean;
import com.fvision.camera.manager.CmdManager;
import com.fvision.camera.util.Cmd_Const;
import com.fvision.camera.utils.CameraStateUtil;
import com.fvision.camera.utils.Const;
import com.fvision.camera.utils.FileUtils;
import com.fvision.camera.utils.LogUtils;
import com.fvision.camera.view.activity.PlaybackActivity;
import com.fvision.camera.view.adapter.HeaderListAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class VideoListFragment extends Fragment {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    private static final String ARG_TYPE = "VIDEO_TYPE";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    /**
     * 0 正常视频 1 紧急和加锁视频 3 图片
     */
    private int videotype = 0;
    private OnListFragmentInteractionListener mListener;
    private StickyListHeadersListView recyclerView;

    public List<FileBean> getFileList() {
        return mFileList;
    }

    private List<FileBean> mFileList = new ArrayList<>();
    private List<FileBean> addFileList = new ArrayList<>();
    private Handler mHandler = new Handler();
    private HeaderListAdapter mAdapter;
    private byte[] files = null;
    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public VideoListFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static VideoListFragment newInstance(byte[] filesByte, int type) {
        VideoListFragment fragment = new VideoListFragment();
        Bundle args = new Bundle();
//        args.putInt(ARG_COLUMN_COUNT, columnCount);
        args.putByteArray(ARG_COLUMN_COUNT,filesByte);
        args.putInt(ARG_TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            files = getArguments().getByteArray(ARG_COLUMN_COUNT);
            videotype = getArguments().getInt(ARG_TYPE);
        }
    }

//    public void setFiles(byte[] bt){
//        files = bt;
//    }

    private final int MAX_PAGE_SIZE = 18;
    private int current_page = 0;


    public void resrefh(){
        final PlaybackActivity mPlaybackActivity = (PlaybackActivity)getActivity();
        files = mPlaybackActivity.loadFile();
        loadFiles();
    }

    public void delItem(String fileName){
        if(TextUtils.isEmpty(fileName)){
            return;
        }
        if(mFileList == null || mFileList.size() < 1){
            return;
        }

        for (FileBean file:mFileList){
            if(file.fileName.equals(fileName)){
                mFileList.remove(file);
                mAdapter.notifyDataSetChanged();
                break;
            }

        }
    }

    public void addItem(FileBean item){
        if(mAdapter == null){
            addFileList.add(item);
        }else {
            mFileList.add(item);
            mAdapter.notifyDataSetChanged();
        }

    }

    /**
     * 获取视频
     */
    private void loadFiles(){
        if(videotype == Cmd_Const.FILE_TYPE_PICTURE){
            loadJpegFiles();
            return;
        }
        if(files == null || files.length < 1){
            return;
        }
        mFileList.clear();
        for(int i = 0; i * Cmd_Const.FILE_BYTE_SIZE < files.length ; i++){
            byte[] item = new byte[Cmd_Const.FILE_BYTE_SIZE];
            System.arraycopy(files,i * Cmd_Const.FILE_BYTE_SIZE,item,0,item.length);
            FileBean file = byte2FileBean(item);
            file.fileIndex = i + 1;
            if(file.fileType != videotype|| file.year <= 1980){//过滤 1979年的视频文件
                continue;
            }
  //          LogUtils.d("files file.dayTime "+file.dayTime +" format "+CameraStateUtil.longToString(file.dayTime,null));
            mFileList.add(file);
        }
        for (FileBean file:addFileList){
            mFileList.add(file);
        }
        //按时间倒序排序
        Collections.sort(mFileList, new ComparatorValues());
        mAdapter.notifyDataSetChanged();
    }

    /**
     * 获取图片
     */
    private void loadJpegFiles(){//这里遍历文件
        if(files == null || files.length < 1){
            return;
        }
        mFileList.clear();
        File root = new File(Const.JPG_PATH);
       // File root = getActivity().getFilesDir();
        File files[] = root.listFiles();
        if(files != null){
            for (File f : files){
                LogUtils.d("file path "+f.getPath());
                if(!f.isDirectory()){
                    FileBean file = new FileBean();
                    file.fileName = f.getName();
                    file.dayTime = f.lastModified();
                    file.fileType = Cmd_Const.FILE_TYPE_PICTURE;

                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(file.dayTime);

                    file.year = calendar.get(Calendar.YEAR);
                    file.month = calendar.get(Calendar.MONTH);
                    file.day = calendar.get(Calendar.DAY_OF_MONTH);
                    file.hour = calendar.get(Calendar.HOUR_OF_DAY);
                    file.minute = calendar.get(Calendar.MINUTE);
                    file.sencond = calendar.get(Calendar.SECOND);
                    LogUtils.d("jpeg file.dayTime "+file.dayTime +" format "+CameraStateUtil.longToString(file.dayTime,null));
                    mFileList.add(file);
                }
            }
            //按时间倒序排序
            Collections.sort(mFileList, new ComparatorValues());
        }
    }

    public static final class ComparatorValues implements Comparator<FileBean> {

        @Override
        public int compare(FileBean o1, FileBean o2) {
            if(o2.dayTime > o1.dayTime){//说明是毫秒
                return 1;
            }else {
                return -1;
            }
//            if(o2.dayTime > 10000000000l){//说明是毫秒
//                o2.dayTime = o2.dayTime/1000;
//            }
//            LogUtils.d("o1.dayTime"+o1.dayTime + " o2.dayTime "+o2.dayTime);
//            return (int)(o2.dayTime - o1.dayTime);
        }
    }

    private FileBean byte2FileBean(byte[] filebyte){
        if(filebyte.length != Cmd_Const.FILE_BYTE_SIZE){
 //           LogUtils.e(" filebyte.length != Cmd_Const.FILE_BYTE_SIZE ");
            return null;
        }
 //       LogUtils.d("filebyte "+CameraStateUtil.bytesToHexString(filebyte));
        FileBean file= new FileBean();
        StringBuffer fileName = new StringBuffer();

        short file_type_num = 0;
        short file_year_month_day = 0;
        short file_hour_minute_second = 0;

        byte[] byte_type_num = new byte[2];
        byte[] byte_year_month_day = new byte[2];
        byte[] byte_hour_minute_second = new byte[2];

        System.arraycopy(filebyte,0,byte_type_num,0,byte_type_num.length);
        System.arraycopy(filebyte,2,byte_year_month_day,0,byte_year_month_day.length);
        System.arraycopy(filebyte,4,byte_hour_minute_second,0,byte_hour_minute_second.length);

        file_type_num = CameraStateUtil.bytesToShort(byte_type_num,0);
        file_year_month_day = CameraStateUtil.bytesToShort(byte_year_month_day,0);
        file_hour_minute_second = CameraStateUtil.bytesToShort(byte_hour_minute_second,0);

        file.year = (file_year_month_day>>9)+1980;
        file.month = (file_year_month_day>>5)&0xF;
        file.day = file_year_month_day&0x1F;
        //(finfo.ftime>>11) , (finfo.ftime>>5)&0x3F , ((finfo.ftime)&0x1F)*2
        file.hour = (file_hour_minute_second  >> 11) & 0x1f ;
        file.minute =  (file_hour_minute_second>>5)&0x3F;
        file.sencond = ((file_hour_minute_second)&0x1F)*2;

 //       LogUtils.d("file.hour "+file.hour+" minute "+file.minute + " sencond "+file.sencond + " file_hour_minute_second "+file_hour_minute_second);

        if((file_type_num & 0x1000) > 1){//加锁
            fileName.append("LOK");
            file.fileType = Cmd_Const.FILE_TYPE_LOCK;
        }else if((file_type_num & 0x8000) > 1){//视频
            fileName.append("MOV");
            file.fileType = Cmd_Const.FILE_TYPE_VIDEO;
        }else if((file_type_num & 0x4000) > 1){//图片
            fileName.append("PHOTO");
            file.fileType = Cmd_Const.FILE_TYPE_PICTURE;
        }else{
            fileName.append("OTHER");
        }

        fileName.append(""+CameraStateUtil.numFormat(file_type_num & 0xfff));//序号

        Calendar calendar = Calendar.getInstance();
        calendar.set(file.year,file.month-1,file.day,file.hour,file.minute,file.sencond);
        file.dayTime = calendar.getTimeInMillis();
//        String timeStr = file.year+"_"+file.month+"_"+file.day+"_"+file.hour+"_"+file.minute+"_"+file.sencond+"_";

      //  fileName.append(CameraStateUtil.longToString(calendar.getTimeInMillis(),"_mm分ss秒"));//"HH时_mm分ss秒"

        if((file_type_num & 0x4000) > 1){//后缀
            fileName.append(".jpg");
        }else{
            fileName.append(".avi");
        }

        file.fileName = fileName.toString();
        return file;
    }

    private short byte2short(byte[] files,int startPos,int length){
        byte[] newByte = new byte[length<2?2:length];
        System.arraycopy(files,startPos,newByte,0,length);
//        LogUtils.d(" newByteShort "+CameraStateUtil.bytesToHexString(newByte));
        return CameraStateUtil.bytesToShort(newByte,0);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_videoitem_list, container, false);

        // Set the adapter
        if (view instanceof StickyListHeadersListView) {
            Context context = view.getContext();
            recyclerView = (StickyListHeadersListView) view;
            mAdapter = new HeaderListAdapter(getActivity(), mFileList, mListener);
            recyclerView.setAdapter(mAdapter);
            recyclerView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Object item = parent.getItemAtPosition(position);
                    if (item instanceof FileBean) {
                        if (mListener != null) {
                            mListener.onListFragmentInteraction((FileBean) item);
                        }
                    }
                }
            });
            //文件长按删除
            recyclerView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    Object item = parent.getItemAtPosition(position);
                    if (item instanceof FileBean) {
                        showDeleteFile((FileBean) item);
                        return true;
                    }
                    return false;
                }
            });
//            //文件长按删除 end
//            if(videotype==3) {
////                if (mColumnCount <= 1) {
////                    recyclerView.setLayoutManager(new LinearLayoutManager(context));
////                } else {
////                    recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
////                }
//                mAdapter = new HeaderListAdapter(getActivity(),mFileList, mListener);
////                recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
////                });
//                recyclerView.setAdapter(mAdapter);
//            }else {
//                if(mFileList.size()>0)
//                initAdapter();
//            }
        }
        if (mFileList.size() <= 0){
            loadFiles();
        }

        return view;
    }

    public void showDeleteFile(final FileBean fileBean) {
        new AlertDialog.Builder(getActivity()).setMessage(R.string.confirm_delete_file)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteFile(fileBean);
                    }
                }).setNegativeButton(R.string.cancel, null).show();
    }

    private void deleteFile(FileBean fileBean) {
        //CmdUtil.getInstance().deleteFile(fileBean.fileType, fileBean.fileName)
        boolean isDelSuccess;
        if(fileBean.fileType == Cmd_Const.FILE_TYPE_PICTURE){
            isDelSuccess = FileUtils.deleteFile(Const.JPG_PATH+fileBean.fileName);
        }else{
            isDelSuccess = CmdManager.getInstance().deleteFile(fileBean.fileName);
        }
        if (isDelSuccess) {
            mFileList.remove(fileBean);
            addFileList.remove(fileBean);
            mAdapter.notifyDataSetChanged();
//            retLoadVideo();
//            ToastUtils.showLongToast(getActivity(),"删除成功 fileIndex "+fileBean.fileIndex);
//            Toast.makeText(getActivity(), R.string.delete_sucess+" fileBean "+fileBean.fileIndex, Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getActivity(), R.string.delete_fail, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getActivity() instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) getActivity();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnListFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(FileBean item);

        void onDownLoad(FileBean item);

        void onDelete(FileBean item);
    }
}
